import React, {useState, useEffect} from 'react';
import jsonCarouselImg from '../../axios/CarouselImg.json'

export default function Carousel({flag}) {
    let images = []
    flag ? images = jsonCarouselImg.data1 : images = jsonCarouselImg.data
    const [currentIndex, setCurrentIndex] = useState(0);
    // 自动轮播功能
    useEffect(() => {
        const interval = setInterval(() => {
            setCurrentIndex((prevIndex) => prevIndex === images.length - 1 ? 0 : prevIndex + 1);
        }, 3000);
        return () => clearInterval(interval);
    }, [images.length]);
    // 上一页功能
    const prevSlide = () => {
        setCurrentIndex((prevIndex) => prevIndex === 0 ? images.length - 1 : prevIndex - 1);
    };
    // 下一页功能
    const nextSlide = () => {
        setCurrentIndex((prevIndex) => prevIndex === images.length - 1 ? 0 : prevIndex + 1);
    };
    return (
        <div className='Carousel'>
            <div id="carouselExampleInterval" className="carousel slide" data-ride="carousel">
                <div className="carousel-inner" style={{maxWidth: 100 + "%", maxHeight: 460}}>
                    {images.map((item, index) => {//轮播图
                        return <div key={index} className={index === currentIndex ? 'slide active' : 'slide'}>
                            {index === currentIndex && (
                                <img className="d-block w-100" src={item.imgUrl} alt={`Slide ${index}`}/>)}
                        </div>
                    })}
                </div>
                <button className="carousel-control-prev" type="button" data-target="#carouselExampleInterval"
                        data-slide="prev" onClick={prevSlide}>
                    <span className="carousel-control-prev-icon" aria-hidden="true"></span>
                    {/* <span className="sr-only"></span> */}
                </button>
                <button className="carousel-control-next" type="button" data-target="#carouselExampleInterval"
                        data-slide="next" onClick={nextSlide}>
                    <span className="carousel-control-next-icon" aria-hidden="true"></span>
                    {/* <span className="sr-only"></span> */}
                </button>
            </div>
            <hr/>
        </div>
    )

}
